package com.heima.media.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.heima.common.dto.ResponseResult;
import com.heima.media.entity.WmSensitive;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsService;
import com.heima.media.service.IWmSensitiveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {

    @Autowired
    private IAuditService auditService;

    @Autowired
    private IWmNewsService newsService;

    @Autowired
    private IWmSensitiveService sensitiveService;

    @GetMapping("/audit/{id}")
    public ResponseResult auditByNewsId(@PathVariable("id") Integer id) {
        auditService.audit(newsService.getById(id));
        return ResponseResult.okResult();
    }

    /**
     * 读excel
     *
     * @param fileName
     * @return
     */
    @PostMapping("/read")
    public ResponseResult read(String fileName) {
        // String fileName = file.getName();
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        // 这里每次会读取3000条数据 然后返回过来 直接调用使用数据就行
        EasyExcel.read(fileName, WmSensitive.class, new PageReadListener<WmSensitive>(dataList -> {
            for (WmSensitive demoData : dataList) {
                log.info("读取到一条数据{}", JSON.toJSONString(demoData));
                // 更新数据到数据库中
                // 查询数据库中是否已有敏感词数据
            }
        })).sheet().doRead();
        return ResponseResult.okResult();
    }


    /**
     * 上传excel
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), WmSensitive.class, new ReadListener() {
            @Override
            public void invoke(Object data, AnalysisContext context) {
                // 每读到一条记录,执行这个方法
                log.info("读取到一条数据{}", JSON.toJSONString(data));
                // 更新数据到数据库中
                // 查询数据库中是否已有敏感词数据
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // 读完所有记录后执行这个方法
                log.info("数据读取完成");
            }
        }).sheet().doRead();
        return ResponseResult.okResult();
    }


    /**
     * 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     *
     * @since 2.1.1
     */
    @GetMapping("downloadFailedUsingJson")
    public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            int i = 1/0;
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), WmSensitive.class).autoCloseStream(Boolean.FALSE).sheet("模板")
                    .doWrite(data());
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    private List<WmSensitive> data() {
        List<WmSensitive> list = sensitiveService.list();
        return list;
    }

}
